package com.suoluo.zenadmin.controllers;

import java.lang.annotation.Annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import net.paoding.rose.web.ControllerInterceptorAdapter;
import net.paoding.rose.web.Invocation;

import com.suoluo.zenadmin.common.CommonResp;

public class JSONInterceptor extends ControllerInterceptorAdapter {
	
	/**
	 *  覆盖这个方法，表示只有标注@JSON的控制器或方法才会被此拦截器拦截
	 */
    @Override
    public Class<? extends Annotation> getRequiredAnnotationClass() {
        return JSON.class;
    }

	@Override
	protected Object after(Invocation inv, Object instruction) throws Exception {
		//转码成json
//		encodeToJSON(inv, instruction);
		CommonResp.encodeResp(inv, instruction);
		// 返回空串给Rose，让其不用再管render的事情了
		return "";

	}
	
	@Override
	public void afterCompletion(Invocation inv, Throwable throwable)
			throws Exception {
		inv.getRequest().removeAttribute("javax.servlet.error.exception_type");
		inv.getRequest().removeAttribute("javax.servlet.error.message");
		inv.getRequest().removeAttribute("javax.servlet.error.exception");
	}
	
//	private void encodeToJSON(Invocation invocation,Object encodeObj) throws IOException{
//		HttpServletResponse response = invocation.getResponse();
//		if (response.getContentType() == null) {
//			response.setContentType("application/json;charset=UTF-8");
//		}
//		Gson gson = new Gson();
//
//		String json = gson.toJson(encodeObj);
//		response.getWriter().write(json);
//	}
	
	@Inherited
	@Target({ ElementType.TYPE, ElementType.METHOD })
	@Retention(RetentionPolicy.RUNTIME)
	@Documented
	public @interface JSON {

	}
	

	
}
